package com.example.saifly.inPageMy;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.common.Activity;
import com.example.common.Application.MyApplication;
import com.example.common.Retrofit.RetrofitHelper;
import com.example.saifly.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

public class DeviceActivity extends Activity
{

    private RecyclerView rvDevice ;
    private ImageView ivReturn;
    private List<Item> deviceList;
    private MyAdapter myAdapter;
    private String id;

    private SharedPreferences sharedPreferences= MyApplication.getContext().getSharedPreferences("config", Context.MODE_PRIVATE);

    @Override
    protected int getContentLayoutId()
    {
        return R.layout.activity_device;
    }

    @Override
    protected void init()
    {
        super.init();
        if(sharedPreferences.getString("identity","default").equals("family")){
            id=sharedPreferences.getString("pid","default");
        }
        else{
            id=sharedPreferences.getString("uid","default");
        }

        ivReturn = findViewById(R.id.device_return);
        rvDevice=findViewById(R.id.device_recyclerView);
        deviceList=new ArrayList<>();
        doJump();

        RecyclerView.LayoutManager layoutManager=new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL);
        rvDevice.setLayoutManager(layoutManager);

        myAdapter=new MyAdapter();
        rvDevice.setAdapter(myAdapter);

        new Thread(new Runnable() {
            @Override
            public void run()
            {
                DeviceList(id);
            }
        }).start();

    }

    private void doJump() {
        ivReturn.setOnClickListener(view -> finish());
    }

    private interface getDeviceInformation {
        @Headers({"Content-Type:application/json"})
        @POST("/manage/getDeviceInformation")
        Call<ResponseBody> DeviceList(@Body JSONObject jsonObject);
    }

    private void DeviceList(String phoneNumber) {
        RetrofitHelper retrofitHelper = new RetrofitHelper();
        Retrofit retrofit = retrofitHelper.getRetrofit();

        getDeviceInformation apiGetDeviceInformation = retrofit.create(getDeviceInformation.class);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("patientPhone", phoneNumber);
//        Log.d("设备", "logData: "+jsonObject);

        Call<ResponseBody> call = apiGetDeviceInformation.DeviceList(jsonObject);
//        Log.d("设备", "logData: "+call);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            String jsonResult=response.body().string();
            JSONObject result = JSON.parseObject(jsonResult);
//            Log.d("设备", "logData: "+result);

            if (result.getInteger("code")!=null&&result.getInteger("code") == 1) {
                //获取的code为1 说明请求成功
//                Log.d("设备", "logData: "+result.getString("result"));
                List<DeviceInformation>device=JSON.parseArray(result.getString("result"),DeviceInformation.class);
//                List<DeviceInformation> device=result.getJSONArray("result").toJavaList(DeviceInformation.class);
                Log.d("设备", "logData: "+device.toString());

                for(int i=0;i<device.size();i++)
                {
                    String deviceId=device.get(i).getId();    //获取设备ID
//                    Log.d("设备", "logData: "+deviceId);
                    String deviceName=device.get(i).getName();   //获取设备名称
//                    Log.d("设备", "logData: "+deviceName);
                    Item item = new Item("123",deviceId,deviceName);
                    deviceList.add(item);
                }
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        Log.d("设备", "run: "+deviceList.toString());
                        myAdapter.replaceData(deviceList);
                        myAdapter.notifyDataSetChanged();
                    }
                });

            } else {
                //请求失败
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        Toast toast=Toast.makeText(DeviceActivity.this, "获取设备信息失败，请重新尝试", Toast.LENGTH_LONG);
                        showMyToast(toast,10*500);// 设置显示时间  一次10ms,显示500次，即显示5s
                    }
                });
            }
        } catch (Exception e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(DeviceActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
    }

    //Toast 自定义显示时长
    public void showMyToast(final Toast toast, final int cnt) {
        final Timer timer =new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                toast.show();
            }
        },0,3000);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                toast.cancel();
                timer.cancel();
            }
        }, cnt );
    }
    private class Item
    {
        String imageUrl;
        String ID;
        String name;
        Item(String imageUrl,String ID,String name)
        {
            this.imageUrl=imageUrl;
            this.ID=ID;
            this.name=name;
        }

        @Override
        public String toString() {
            return "Item{" +
                    "imageUrl='" + imageUrl + '\'' +
                    ", ID='" + ID + '\'' +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
    private class MyAdapter extends BaseQuickAdapter<Item, BaseViewHolder>
    {
        public MyAdapter()
        {
            super(R.layout.holder_device_rv, deviceList);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder holder, Item item)
        {
            Glide.with(getBaseContext()).load(R.drawable.home_device).into((ImageView) holder.getView(R.id.holder_device_imageUrl));

            holder.setText(R.id.holder_device_number,item.ID);
            holder.setText(R.id.holder_device_name,item.name);
        }
    }
}
